﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crawler_v1.service.impl;
using System.Windows.Forms;
using System.Threading;

namespace Crawler_v1.spider
{
    class ContentPraser
    {
        private Queue queue;//url队列

        private WebKitCrawler2 c2;

        private string curUrl;

        public string getCurUrl()
        {
            return curUrl;
        }

        public ContentPraser(Form form,Queue queue)
        {
            
            c2 = new WebKitCrawler2(form);
            this.queue = queue;
        }

        public void parse(string url, Action actionFinish)
        {
            c2.init("http://fec.mofcom.gov.cn/article/fwydyl/zgzx/");
            c2.onGet(new WebKitCrawler2.task(() =>
            {
                c2.addJs("columnlist.js");
                //string str = c2.WebKitBrowser1.Document.InvokeScriptMethod("getColumnList", new object[] { }) as string;
                Console.WriteLine("we parse " + url + " 成功");
            }));
            c2.onTaskFinish += new WebKitCrawler2.task(() =>
            {
                actionFinish();
                Console.WriteLine("taskFinish");
            });
        }

        public void toParse(Action<ContentPraser> actionNext)
        {

            curUrl = queue.getOneUrl();
            c2.init(curUrl);
            c2.onGet(new WebKitCrawler2.task(() =>
            {
                c2.addJs("columnlist.js");
                //string str = c2.WebKitBrowser1.Document.InvokeScriptMethod("getColumnList", new object[] { }) as string;
                Console.WriteLine("we parse " + curUrl + " 成功");
            }));
            c2.onTaskFinish += new WebKitCrawler2.task(() =>
            {
                //解析完成

                actionNext(this);

                Console.WriteLine("taskFinish");
            });
            
        }

        public void startWorker(Action<ContentPraser> actionNext)
        {
            if (!queue.isEnded())
            {
                //等待队列获得新的url
                if (!queue.IsEmpty())
                {
                    toParse(actionNext);
                }
                else
                {
                    //队列解析更多url
                    queue.parseNew(new Action(() =>
                    {
                        //队列完毕
                        toParse(actionNext);
                    }));
                }
            }
        }
    }
}
